import { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';

interface SystemInfo {
  cpuUsage: number;
  memoryUsage: {
    used: number;
    total: number;
    percentage: number;
  };
  diskUsage: {
    used: number;
    total: number;
    percentage: number;
  };
  networkStatus: 'online' | 'offline';
  platform: string;
  version: string;
}

export const useSystemInfo = () => {
  const [systemInfo, setSystemInfo] = useState<SystemInfo>({
    cpuUsage: 0,
    memoryUsage: { used: 0, total: 0, percentage: 0 },
    diskUsage: { used: 0, total: 0, percentage: 0 },
    networkStatus: 'online',
    platform: '',
    version: '1.0.0',
  });
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchSystemInfo = async () => {
      try {
        // 模拟系统信息获取，实际项目中会调用Tauri后端
        const mockSystemInfo: SystemInfo = {
          cpuUsage: Math.random() * 100,
          memoryUsage: {
            used: Math.floor(Math.random() * 8) + 2,
            total: 16,
            percentage: Math.floor(Math.random() * 60) + 20,
          },
          diskUsage: {
            used: Math.floor(Math.random() * 500) + 100,
            total: 1024,
            percentage: Math.floor(Math.random() * 60) + 20,
          },
          networkStatus: 'online',
          platform: navigator.platform,
          version: '1.0.0',
        };

        setSystemInfo(mockSystemInfo);
        setIsLoading(false);
      } catch (err) {
        setError('获取系统信息失败');
        setIsLoading(false);
      }
    };

    fetchSystemInfo();
    
    // 定期更新系统信息
    const interval = setInterval(fetchSystemInfo, 5000);
    
    return () => clearInterval(interval);
  }, []);

  const refreshSystemInfo = async () => {
    setIsLoading(true);
    setError(null);
    
    try {
      // 重新获取系统信息
      const mockSystemInfo: SystemInfo = {
        cpuUsage: Math.random() * 100,
        memoryUsage: {
          used: Math.floor(Math.random() * 8) + 2,
          total: 16,
          percentage: Math.floor(Math.random() * 60) + 20,
        },
        diskUsage: {
          used: Math.floor(Math.random() * 500) + 100,
          total: 1024,
          percentage: Math.floor(Math.random() * 60) + 20,
        },
        networkStatus: 'online',
        platform: navigator.platform,
        version: '1.0.0',
      };

      setSystemInfo(mockSystemInfo);
    } catch (err) {
      setError('刷新系统信息失败');
    } finally {
      setIsLoading(false);
    }
  };

  return {
    systemInfo,
    isLoading,
    error,
    refreshSystemInfo,
  };
};